/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.WebIDE.ejb.sessions;

import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.transaction.UserTransaction;
import org.WebIDE.ejb.entities.*;

import org.WebIDE.ejb.sessions.exceptions.*;

/**
 *
 * @author huy
 */
@Stateless
public class RepliesFacade implements RepliesFacadeLocal, RepliesFacadeRemote {
    @Resource
    private UserTransaction utx = null;
    @PersistenceContext(unitName = "WebIDE-ejbPU")
    private EntityManager _em = null;
/*
    public void create(Replies replies) {
        _em.persist(replies);
    }

    public void edit(Replies replies) {
        _em.merge(replies);
    }
*/
    public void remove(Replies replies) {
        _em.remove(_em.merge(replies));
    }

    public Replies find(Object id) {
        return _em.find(Replies.class, id);
    }

    public List<Replies> findAll() {
        return _em.createQuery("select object(o) from Replies as o").getResultList();
    }

    public EntityManager getEntityManager() {
        return _em;
    }

    public void create(Replies replies) throws PreexistingEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            //utx.begin();
            //replies.setContent("xin chào các bạn");
            em = getEntityManager();
            Topics topicId = replies.getTopicId();
            if (topicId != null) {
                topicId = em.getReference(topicId.getClass(), topicId.getId());
                replies.setTopicId(topicId);
            }
            Users userName = replies.getUserName();
            if (userName != null) {
                userName = em.getReference(userName.getClass(), userName.getUserName());
                replies.setUserName(userName);
            }
            em.persist(replies);
            if (topicId != null) {
                topicId.getRepliesCollection().add(replies);
                topicId = em.merge(topicId);
            }
            if (userName != null) {
                userName.getRepliesCollection().add(replies);
                userName = em.merge(userName);
            }
            //utx.commit();
        } catch (Exception ex) {
            try {
                //utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findReplies(replies.getId()) != null) {
                throw new PreexistingEntityException("Replies " + replies + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                //em.close();
            }
        }
    }

    public void edit(Replies replies) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            //utx.begin();

            em = getEntityManager();
            Replies persistentReplies = em.find(Replies.class, replies.getId());
            Topics topicIdOld = persistentReplies.getTopicId();
            Topics topicIdNew = replies.getTopicId();
            Users userNameOld = persistentReplies.getUserName();
            Users userNameNew = replies.getUserName();
            if (topicIdNew != null) {
                topicIdNew = em.getReference(topicIdNew.getClass(), topicIdNew.getId());
                replies.setTopicId(topicIdNew);
            }
            if (userNameNew != null) {
                userNameNew = em.getReference(userNameNew.getClass(), userNameNew.getUserName());
                replies.setUserName(userNameNew);
            }
            replies = em.merge(replies);
            if (topicIdOld != null && !topicIdOld.equals(topicIdNew)) {
                topicIdOld.getRepliesCollection().remove(replies);
                topicIdOld = em.merge(topicIdOld);
            }
            if (topicIdNew != null && !topicIdNew.equals(topicIdOld)) {
                topicIdNew.getRepliesCollection().add(replies);
                topicIdNew = em.merge(topicIdNew);
            }
            if (userNameOld != null && !userNameOld.equals(userNameNew)) {
                userNameOld.getRepliesCollection().remove(replies);
                userNameOld = em.merge(userNameOld);
            }
            if (userNameNew != null && !userNameNew.equals(userNameOld)) {
                userNameNew.getRepliesCollection().add(replies);
                userNameNew = em.merge(userNameNew);
            }
            //utx.commit();
        } catch (Exception ex) {
            try {
                //utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = replies.getId();
                if (findReplies(id) == null) {
                    throw new NonexistentEntityException("The replies with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                //em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            //utx.begin();
            em = getEntityManager();
            Replies replies;
            try {
                replies = em.getReference(Replies.class, id);
                replies.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The replies with id " + id + " no longer exists.", enfe);
            }
            Topics topicId = replies.getTopicId();
            if (topicId != null) {
                topicId.getRepliesCollection().remove(replies);
                topicId = em.merge(topicId);
            }
            Users userName = replies.getUserName();
            if (userName != null) {
                userName.getRepliesCollection().remove(replies);
                userName = em.merge(userName);
            }
            em.remove(replies);
            //utx.commit();
        } catch (Exception ex) {
            try {
                //utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                //em.close();
            }
        }
    }

    public List<Replies> findRepliesEntities() {
        return findRepliesEntities(true, -1, -1);
    }

    public List<Replies> findRepliesEntities(int maxResults, int firstResult) {
        return findRepliesEntities(false, maxResults, firstResult);
    }

    private List<Replies> findRepliesEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Replies as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            //em.close();
        }
    }

    public Replies findReplies(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Replies.class, id);
        } finally {
            //em.close();
        }
    }

    public int getRepliesCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Replies as o").getSingleResult()).intValue();
        } finally {
            //em.close();
        }
    }

    // my code
    public int getRepliesCount(Topics topicID) {
        EntityManager em = getEntityManager();
        try {
            Query query = em.createQuery("select count(o) from Replies as o where o.topicId=:tid");
            query.setParameter("tid", topicID);
            return ((Long)query.getSingleResult()).intValue(); 
        } finally {
            //em.close();
        }
    }
    
    public List<Replies> getReplies(Topics topicID) {
        EntityManager em = getEntityManager();
        try {
            Query query = em.createQuery("select object(o) from Replies as o where o.topicId=:tid");
            query.setParameter("tid", topicID);
            return query.getResultList();
        } finally {
            
        }
    } 
    
    public List<Object> getLastModified(Topics topicID) {
        EntityManager em = getEntityManager();
        try {
            Query query = em.createQuery("select MAX(r.modified) from Replies r where r.topicId=:tid");
            query.setParameter("tid", topicID);
            Date lastDate = (Date) query.getSingleResult();
            Query q = em.createQuery("select r.modified, r.userName from Replies r where r.modified=:lastdate");
            q.setParameter("lastdate", lastDate);
            return q.getResultList();
        } finally {
            //em.close();
        }
    }
    
    public int getMaxID() {
        EntityManager em = getEntityManager();
        try {
            Integer kq = ((Integer)em.createQuery("select MAX(r.id) from Replies r").getSingleResult());
            if (kq == null)
                return 0;
            return kq.intValue();
        } finally {
            
        }
    }
}
